<template>
  <el-dialog
    title="批量导出"
    :visible.sync="visible"
    width="600px"
    :destroy-on-close="true"
    :before-close="handleClose"
  >
    <div class="import-wrap" v-if="visible">
      <el-scrollbar class="scroll">
        <el-form :model="form" ref="form" label-width="83px" class="radio-wrap">
          <el-form-item
            label="导出类型:"
            prop="confId"
            :rules="[
              { required: true, message: '导出类型不能为空', trigger: 'change' }
            ]"
          >
            <el-radio-group
              v-model="form.confId"
              @change="handleFileTypeChange"
            >
              <el-radio label="1">全部数据</el-radio>
              <el-radio
                v-for="item in typeList"
                :label="item.confId"
                :key="item.confId"
                >{{ item.name }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <template
            v-if="
              form.confId != '1' &&
              configObj.selectCondition &&
              configObj.selectCondition.length > 0
            "
          >
            <el-form-item
              v-for="item in configObj.selectCondition"
              :key="item.setKey"
              :label="item.name"
            >
              <template v-if="getComponentType(item.componentType) == 1">
                <ComponentOne
                  :formItem="item"
                  @change="handleFormChange"
                ></ComponentOne>
              </template>
            </el-form-item>
          </template>
        </el-form>
      </el-scrollbar>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" :loading="exportLoading" @click="handleConfirm"
        >确 定</el-button
      >
    </span>
    <LoadingProgress
      :loading="modalLoading"
      :text="loadingText"
      :percentage="percentage"
    ></LoadingProgress>
  </el-dialog>
</template>

<script>
import { download } from '@/utils/fileSaver';
import { offlineGetResult, offlineBatchExport } from '@/api/index';
import { componentTypeMap } from '@/utils/dataMap';
import ComponentOne from './OfflineRegisterInfo/ComponentOne';
import LoadingProgress from '@/components/LoadingProgress';
export default {
  components: {
    ComponentOne,
    LoadingProgress
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    cardType: {
      type: [String, Number],
      default: ''
    },
    typeList: {
      type: Array,
      default: () => []
    },
    configObj: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      form: {
        confId: '1'
      },
      templateUrl: '',
      isExportAll: false,
      fileList: [],
      timer: null,
      retryCount: 0,
      MAX_RETRY_TIMES: 1000,
      exportLoading: false,
      percent: '0.00',
      redisId: '',
      percentage: 0,
      modalLoading: false,
      loadingText: ''
    };
  },
  methods: {
    offlineBatchExportFn() {
      const temp = [];
      if (
        this.configObj.selectCondition &&
        this.configObj.selectCondition.length > 0
      ) {
        this.configObj.selectCondition.forEach((item) => {
          if (item.setValue) {
            if (
              item.componentType === 'datePickerRange' &&
              item.setValue.length > 0
            ) {
              temp.push({
                setKey: item.setKey,
                setValue: item.setValue.join(',')
              });
            }
            if (item.componentType !== 'datePickerRange') {
              temp.push({
                setKey: item.setKey,
                setValue: item.setValue
              });
            }
          }
        });
      }
      if (temp.length == 0) {
        this.$message.error('请至少选择一个条件！');
        return;
      }
      this.loadingText = `正在导出数据，已完成${'' + this.percentage}%`;
      this.modalLoading = true;
      const params = {
        cardType: this.cardType,
        confId: this.form.confId,
        setCode: this.configObj.setCode,
        condition: temp
      };
      offlineBatchExport(params)
        .then((res) => {
          if (res.code == 200) {
            this.redisId = res.data;
            setTimeout(() => {
              this.startRequest();
            }, 5000);
          } else {
            this.$message.error(res.data.status_desc);
          }
        })
        .catch((err) => {
          this.modalLoading = false;
          this.percentage = 0;
          this.$message.error('导出失败，请重试！');
        });
    },
    offlineGetResultFn() {
      this.retryCount++;
      offlineGetResult({ redisId: this.redisId })
        .then((res) => {
          if (res.code == 200) {
            if (res.data.code == 1) {
              // res.data 是一个url的话，直接下载
              this.endRequest();
              download(res.data.fileUrl, res.data.fileName);
              this.$message.success('数据导出成功');
              this.handleClose();
            } else if (res.data.code == 2) {
              // 导出失败
              this.endRequest();
              this.$message.error('此日期范围无数据或者服务器繁忙，请稍后再试');
            } else {
              // 正在导出
              this.percentage = +res.data.percent;
              this.loadingText = `正在导出数据，已完成${'' + this.percentage}%`;
            }
          } else {
            this.$message.error(res.status_desc);
            this.endRequest();
          }
        })
        .catch((err) => {
          this.$message.error(err);
          this.endRequest();
        });
    },
    startRequest() {
      this.timer = setInterval(() => {
        if (this.retryCount < this.MAX_RETRY_TIMES) {
          this.offlineGetResultFn();
        } else {
          this.$message.error('超过最大的重试次数，请稍后重试！');
          clearInterval(this.timer);
          this.modalLoading = false;
          this.percentage = 0;
        }
      }, 5000);
    },
    endRequest() {
      clearInterval(this.timer);
      this.exportLoading = false;
      this.timer = null;
      this.modalLoading = false;
      this.percentage = 0;
    },
    handleFormChange(key, val) {
      this.$set(this.form, key, JSON.parse(val));
    },
    handleFileTypeChange(val) {
      if (val == '1') {
        this.isExportAll = true;
      } else {
        this.isExportAll = false;
        this.form.confId = val;
        // const temp = this.typeList.find((item) => item.confId === val);
        // this.templateUrl = temp.templateUrl;
      }
    },
    handleClose() {
      this.refreshCondition();
      Object.keys(this.form).forEach((key) => {
        this.form[key] = '';
      });
      this.form.confId = '1';
      this.isExportAll = false;
      this.$emit('update:visible', false);
    },
    handleConfirm() {
      if (this.isExportAll) {
        this.$emit('exportAll');
        this.handleClose();
      } else {
        this.offlineBatchExportFn();
      }
    },
    getComponentType(type) {
      return componentTypeMap[type];
    },
    refreshCondition() {
      this.configObj.selectCondition.forEach((item) => {
        if (item.componentType === 'datePickerRange') {
          item.setValue = [];
        } else {
          item.setValue = '';
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 0;
}
.import-wrap {
  color: #9c9ca1;
  // height: 210px;
  .scroll {
    height: 100%;
  }
  .radio-wrap {
    padding: 18px;
  }
  .import-cont {
    align-items: flex-start;
    padding: 18px 18px 10px 18px;
    border: 1px solid #d2d5e1;
    border-radius: 6px;
    margin-bottom: 12px;
  }
}
.icon {
  margin-right: 24px;
}
.sub-title {
  margin: 8px 0 4px 0;
}
.import-tips {
  background-color: #f5f9ff;
  border-radius: 2px;
  padding: 16px 24px;
  color: #b8b9be;
  .danger {
    color: #ec4343;
    margin-right: 8px;
  }
  .blue {
    padding-top: 8px;
    color: $primary-color;
    &.step-2 {
      padding: 0;
    }
  }
}
.dialog-footer.step {
  justify-content: space-between;
}
.red {
  margin: 0 0 12px 0;
}
.success-cont {
  padding: 64px 25%;
  align-items: flex-start;
  font-size: 12px;
  .icon {
    margin-right: 16px;
  }
}
.is-flex {
  display: flex;
  align-items: center;
}
</style>
